package com.supinfo.suptracking.servlet;

import com.supinfo.suptracking.entity.User;
import com.supinfo.suptracking.service.UserService;
import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Fabien, Jérémy, Ludovic, Brice
 */

@WebServlet(name = "LoginServlet", urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
    
    @EJB
    private UserService userService;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect(getServletContext().getContextPath() + "/jsp/login.jsp");		
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        List<User> userInDB = userService.processGetAllUser();
        System.out.println(userInDB);
        boolean islogged = false;
        for (User user : userInDB) {
            System.out.println("|" + user.getUserName() + "|" + username + "| - |" + user.getPassword() + "|" + password + "|");
            if(user.getUserName().equals(username) && user.getPassword().equals(password)){
                islogged=true;
                req.getSession().setAttribute("userlogged", user);
                break;
            }
        }
        if (islogged) {
            System.out.println("User is logged ! ");
            resp.sendRedirect(getServletContext().getContextPath() + "/profile");
        }
        else{
            req.getSession().setAttribute("event", "0");
            req.getSession().setAttribute("message", "Username or password is incorrect");
            System.out.println("le password n'est pas bon");
            resp.sendRedirect(getServletContext().getContextPath() + "/login"); 
        }
    }
}
